import { useGetRoomListQuery,useDelRoomIdsMutation }  from '@/store/toolkit/ApiSlice.js'
import { Alert, Flex, Spin } from 'antd';
import {useState} from 'react'
function RtkQuery() {
    const [page, setPage] = useState(1); // 记录当前页数

    const {
        data:list,
        isLoading,
        isSuccess,
        isError,
        error,
        refetch // 获取 refetch 方法
    } = useGetRoomListQuery({pageCode:page,pageSize:20})

    const [delRoomIds,{isLoading:delLoading}] = useDelRoomIdsMutation()
    // 下一页
    const nextPage = ()=>{
        setPage(pre=>pre+1)
    }
       // 删除一条
    const delIds = async (params) => {
        try {
           const data =  await delRoomIds(params).unwrap(); // unwrap() 用来确保 mutation 完成
        //    console.log('data', data);
            refetch(); // 删除成功后触发重新获取数据
        } catch (error) {
            console.error('删除失败', error);
        }
    }

    const ShowItem = ({source,calback})=>{
        const {title,sizeRoom,url,price,id} = source
        return (
            <>
            <h3>名称： <span dangerouslySetInnerHTML={{ __html: title }} /></h3>
            <p><img src={url}></img></p>
            <p>户型：{sizeRoom}居</p>
            <p>价格：{price}万</p>
            <button onClick={()=>{calback(id)}}>删除</button>
            </>
        )
    }
    let content;
    if(list){
        if(isError){
            content = <div>接口请求报错{error}</div>
        }else{
            content= list.data.list.map(item=><ShowItem source={item} calback={delIds}/>)
        }
    }

    return (  <div>
         <Spin spinning={isLoading} delay={500}>
                 <button onClick={nextPage}>下一页</button>
            {content}
       
         </Spin>
    </div>);
}

export default RtkQuery;